<?php
class Mysql {

    protected $db;
    public $lastInsertId;

    public function __construct(){
        $this->app = Basic::app();
        $config = $this->app->getConfigs();
        $db_config = $config['db']['mysql'];
        $dns = "mysql:host={$db_config['host']};dbname={$db_config['dbname']}";
        $this -> db = new PDO($dns,$db_config['user'],$db_config['password']);
    }

    /**
     * 执行sql语句
     * @param unknown_type $sql
     */
    public function query($sql){
    	Debug::record("before sql execute():".$sql);
        $stmt = $this->db->query($sql);
        Debug::record("after sql execute():".$sql);
        if($stmt){
        	if($this->db->lastInsertId()){
        		Debug::record("lastInsertId:".$this->db->lastInsertId());
        		return $this->db->lastInsertId();
        	}
            return $stmt;
        }else{
            return false;
        }
    }


    /**
     * 从数组中插入数据
     * @param array $data 待插入数据 若不为数组，直接返回false
     * @param array $where 插入条件
     *
     */
    public function insert($table, $data){
        if(!is_array($data)){
            return null;
        }
        $array_keys = array_keys($data);
        $array_values = array_values($data);
        $keys = implode(',',$array_keys);
        foreach($array_values as &$v){
            if(!is_float($v)&&!is_int($v)){
                $v = "'".$v."'";
            }
        }
        $values = implode(',',$array_values);
        $sql = "insert into {$table}({$keys}) values ({$values});";
        return $this->query($sql);
    }

    public function update($table, $data, $where){
        if(count($data)==0||count($where)==0){
            return null;
        }
        $_array1 = array();
        foreach($data as $k=>$v){
            $_array1[] = "{$k}='{$v}'";
        }
        $_data = implode(',',$_array1);

        $_array2 = array();
        foreach($where as $k=>$v){
            $_array2[] = "{$k}='{$v}'";
        }
        $_where = implode(' and ',$_array2);

        $sql = "update {$table} set {$_data} where $_where";
        return $this->query($sql);
    }

    public function fetchAll($sql){
        if($stmt = $this->query($sql)){
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }else{
            return null;
        }
    }

    public function fetch($sql){
        if($stmt = $this->query($sql)){
            return $stmt->fetch(PDO::FETCH_ASSOC);
        }else{
            return null;
        }
    }



}